package com.vchello.service.log;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.vchello.bean.message.Message;
import com.vchello.bean.user.User;
import com.vchello.service.message.MessageService;
import com.vchello.util.Utility;

/**
 * 
 * @author power
 *
 */
@Component
@Aspect
public class UserLog {
	
	@Autowired
	private MessageService messageService;

	/**
	 * 添加业务逻辑方法切入点
	 */
	@Pointcut("execution(* com.vchello.service.user.UserService.save*(..))")
	public void insertServiceCall() {
	}

	@AfterReturning(value = "insertServiceCall() &&args(user,..)", argNames = "user")
	public void insertServiceCallCalls(JoinPoint joinPoint, User user) throws Throwable {
		if (joinPoint.getArgs() == null) {
			return;
		}

		String methodName = joinPoint.getSignature().getName();
		System.out.println(methodName);
		if(null == user) {
			return;
		}
		String content = "欢迎使用VChello SaaS，管理属于你的独角兽项目。关注微信服务号vchellohelp，获取新项目投递提醒，机构最新动态等消息！如有疑问，可直接到反馈链接进行反馈。";
		messageService.saveMessage(new Message(2, user.getId(), "注册通知", 1, 1, 1, content, Utility.getSimpleFormatedDayNow()));  //保存消息
		System.out.println("开始保存日志");
	}

	@Before(value = "insertServiceCall() &&args(user,..)", argNames = "user")
	public void before(JoinPoint joinPoint, User user) {
		System.out.println("beforeSing");
		System.out.println("object=" + user.getUserName());
	}

	@Around(value = "execution(* com.vchello.service.user.UserService.save*(..)) && args(user,..)", argNames = "user")
	public Object doConcurrentOperation(ProceedingJoinPoint pjp, User user) throws Throwable {
		Object result = null;
		String methodName = pjp.getSignature().getName();
		try {
			System.out.println("The method " + methodName + " begins with =" + user.getUserName());
			// if(status != 1) {
			result = pjp.proceed();
			System.out.println("The method " + methodName + " ends with " + Arrays.asList(pjp.getArgs()));
			// }
		} catch (Throwable e) {
			System.out.println("The method " + methodName + " occurs expection : " + e);
			throw new RuntimeException(e);
		}
		System.out.println("The method " + methodName + " ends");
		System.out.println("result=" + result);
		return result;
	}
}
